/*
 * Copyright (c) 2020 hebeiyiliuba.com
 * All rights reserved.
 *
 */
package org.jeecg.modules.third.sendsms.util;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.StatusLine;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.annotation.PostConstruct;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.URI;
import java.net.URL;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * Http
 *
 * @author duanlikao
 * @created 2020/11/30
 */
public class HttpUtil {

    private static final Logger LOGGER = LoggerFactory.getLogger(HttpUtil.class);
    private static Integer timeout = 5000;

    public static String doGet(String url) {
        CloseableHttpClient client = HttpClients.createDefault();
        try {
            //发送get请求
            HttpGet request = new HttpGet(url);
            //设置请求和传输超时时间
            RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(HttpUtil.timeout).
                    setConnectTimeout(HttpUtil.timeout).build();
            request.setConfig(requestConfig);
            CloseableHttpResponse response = client.execute(request);
//            LOGGER.info("doGet.response:url={} response={}", url, response);
            try {
                /**请求发送成功，并得到响应**/
                if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                    /**读取服务器返回过来的json字符串数据**/
                    String strResult = EntityUtils.toString(response.getEntity());
//                    LOGGER.info("HttpUtil.doGet.res:url={} strResult={}", url, strResult);
                    return strResult;
                }
            } catch (Exception e) {
                LOGGER.error("doGet.exception: e={}", e);
            } finally {
                response.close();
            }

        } catch (Exception e) {
            LOGGER.error("HttpUtil.doGet.exception:url={} e={}", url, e);
        } finally {
            try {
                client.close();
            } catch (IOException e) {
                LOGGER.error("doGet.exception:close client fail");
            }
        }

        return null;
    }

    public static String doPost(String url, Map params){
        BufferedReader in = null;
        try {
            // 定义HttpClient
            HttpClient client = new DefaultHttpClient();
            // 实例化HTTP方法
            HttpPost request = new HttpPost();
            request.setURI(new URI(url));

            //设置参数
            List <NameValuePair> nvps = new ArrayList <NameValuePair>();
            for (Iterator iter = params.keySet().iterator(); iter.hasNext();) {
                String name = (String) iter.next();
                String value = String.valueOf(params.get(name));
                nvps.add(new BasicNameValuePair(name, value));
            }
            request.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));

            HttpResponse response = client.execute(request);
            int code = response.getStatusLine().getStatusCode();
            //请求成功
            if(code == 200){
                in = new BufferedReader(new InputStreamReader(response.getEntity()
                        .getContent(),"utf-8"));
                StringBuffer sb = new StringBuffer("");
                String line = "";
                String NL = System.getProperty("line.separator");
                while ((line = in.readLine()) != null) {
                    sb.append(line + NL);
                }

                in.close();

                return sb.toString();
            } else{	//
                LOGGER.info("HttpUtil.doPost.error: url={} params={} code={}", url, params, code);
                return null;
            }
        } catch(Exception e){
            LOGGER.error("HttpUtil.doPost.exception: url={} params={} e={}", url, params, e);
            return null;
        }
    }

    /**
     * post请求（用于请求json格式的参数）
     * @param url
     * @param params
     * @return
     */
    public static String doPost(String url, String params) throws Exception {
        CloseableHttpClient httpclient = HttpClients.createDefault();
        // 创建httpPost
        HttpPost httpPost = new HttpPost(url);
        httpPost.setHeader("Accept", "application/json");
        httpPost.setHeader("Content-Type", "application/json");
        String charSet = "UTF-8";
        StringEntity entity = new StringEntity(params, charSet);

        httpPost.setEntity(entity);
        CloseableHttpResponse response = null;

        try {
            response = httpclient.execute(httpPost);
            StatusLine status = response.getStatusLine();
            int state = status.getStatusCode();
            if (state == HttpStatus.SC_OK) {
                HttpEntity responseEntity = response.getEntity();
                String jsonString = EntityUtils.toString(responseEntity);
                return jsonString;
            }
            else{
                LOGGER.info("HttpUtil.doPost.error:url={} params={} response={}", url, params, response);
            }
        } finally {
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                    LOGGER.error("HttpUtil.doPost.exception.response.close:e={}", e);
                }
            }
            try {
                httpclient.close();
            } catch (IOException e) {
                LOGGER.error("HttpUtil.doPost.exception.httpclient.close:e={}", e);
            }
        }
        return null;
    }

    /**
     * 短信推送
     * @param url
     * @param body
     * @return
     * @throws Exception
     */
    @PostConstruct
    public static String doPostSms(String url, Map<String, Object> body) throws Exception {
        HttpsURLConnection connection = null;
        InputStream is = null;
        BufferedReader br = null;
        trustAllHttpsCertificates();
        try {
            URL realUrl = new URL(url);
            connection = (HttpsURLConnection) realUrl.openConnection();
            connection.setHostnameVerifier(DO_NOT_VERIFY);
            // 设置可输入
            connection.setDoInput(true);
            // 设置该连接是可以输出的
            connection.setDoOutput(true);
            // 设置请求方式
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
            connection.connect();
            ObjectMapper objectMapper = new ObjectMapper();
            PrintWriter pw = new PrintWriter(new OutputStreamWriter(connection.getOutputStream(), "UTF-8"));
            pw.write(objectMapper.writeValueAsString(body));
            pw.flush();
            pw.close();
            br = new BufferedReader(new InputStreamReader(connection.getInputStream(), "utf-8"));
            int status = connection.getResponseCode();
            if (200 == status) {
                is = connection.getInputStream();
            } else { // 400/401
                is = connection.getErrorStream();
            }
            br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
            String line = null;
            StringBuilder result = new StringBuilder();
            // 读取数据
            while ((line = br.readLine()) != null) {
                result.append(line + "\n");
            }
            connection.disconnect();
            return result.toString();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (null != is) {
                    is.close();
                }
                if (null != br) {
                    br.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return null;
    }
    /**
     * 设置不验证主机
     */
    private static final HostnameVerifier DO_NOT_VERIFY = new HostnameVerifier() {
        @Override
        public boolean verify(String hostname, SSLSession session) {
            return true;
        }
    };

    static void trustAllHttpsCertificates() throws Exception {
        TrustManager[] trustAllCerts = new TrustManager[] {
                new X509TrustManager() {
                    @Override
                    public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                        return;
                    }


                    @Override
                    public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                        return;
                    }


                    @Override
                    public X509Certificate[] getAcceptedIssuers() {
                        return null;
                    }
                }
        };
        SSLContext sc = SSLContext.getInstance("SSL");
        sc.init(null, trustAllCerts, null);
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
    }

}
